import pika, sys, os

def main():
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
    channel = connection.channel()

    channel.queue_declare(queue='hello')


    def callback(ch, method, properties, body):#定义callback打印消息内容
        print(" [x] Received %r" % body)

    # 我们需要告诉RabbitMQ这个特定的callback应该从我们的hello队列接受消息；默认情况下是启动手动消息确认，通过auto_ack=True标志明确的关闭他们
    channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)

    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()
# 进入一个永无止境的循环，等待数据并在必要时运行回调，并在程序关闭期间捕获KeyboardInterrupt
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)